import * as DOM from "../functions/dom/domtool.js";
import { ImgTool, MyRect, TTImgData } from "../functions/image/image.js";
import { IO, TTPathTool } from "../common/io.js";

export async function Tool_AtlasPackInit()
{
    DOM.DomTool.Init();

    let panel1 = DOM.DomTool.AddPanel();
    panel1.AddChild(new DOM.Label("图集打包工具"));
    panel1.AddChild(new DOM.Button("检查文件", () => {
        checkFile(textbox.getValue(), panel);
    }));
    panel1.AddChild(new DOM.Button("打包", () => {
        let srcpath = textbox.getValue();
        let texw = parseInt(textwidth.getValue())
        let texh = parseInt(textheight.getValue())
        let border = parseInt(textborder.getValue());
        let cutborder = togglecutborder.getValue();
        packFile(srcpath, texw, texh, border, cutborder
            , panelResult);
    }));
    DOM.DomTool.AddLabel("和VSCode Ext 兼容的图集打包程序");
    let textbox = DOM.DomTool.AddTextBox("打包碎图位置（目录)", "pictures");
    let textwidth = DOM.DomTool.AddTextBox("打包宽度", "1024");
    let textheight = DOM.DomTool.AddTextBox("打包高度", "1024");
    let textborder = DOM.DomTool.AddTextBox("打包边距", "1");
    let togglecutborder = DOM.DomTool.AddToggle("裁剪透明边", true);
    let panelResult = DOM.DomTool.AddPanel();
    let panel = DOM.DomTool.AddPanel();


    try {
        let editjson = JSON.parse(await IO.LoadEditFile_AsText());
        let srcpath = editjson["packoption"]["srcpath"];
        let width = editjson["packoption"]["packwidth"];
        let height = editjson["packoption"]["packheight"];
        let border = editjson["packoption"]["border"];
        let cutborder = editjson["packoption"]["cutborder"] as boolean;
        if (srcpath != undefined)
            textbox.setValue(srcpath);
        if (width != undefined)
            textwidth.setValue(width.toString());
        if (height != undefined)
            textheight.setValue(height.toString());
        if (border != undefined)
            textborder.setValue(border.toString());
        if (cutborder != undefined)
            togglecutborder.setValue(cutborder);
        console.log("load edit succ");
    }
    catch
    {
        console.log("load edit fail.");
    }

    console.log("hi");
}

async function checkFile(path: string, panel: DOM.Panel) {
    let fs = await IO.FindFile(path, 3);

    panel.RemoveAllChild();
    for (var i = 0; i < fs.length; i++) {
        panel.AddChild(new DOM.Label(fs[i].name + " : " + fs[i].size));

        if (fs[i].name.toLowerCase().includes(".png")) {
            let buf = await IO.LoadBinaryFile(fs[i].name);
            let url = ImgTool.Bin2Url(buf);
            panel.AddChild(new DOM.Picture(url));
        }
    }
}
async function packFile(path: string, width: number, height: number, border: number, cutborder: boolean, panel: DOM.Panel) {
    let fs = await IO.FindFile(path, 3);
    panel.RemoveAllChild();

    let srcrect: MyRect[] = [];
    for (var i = 0; i < fs.length; i++) {
        let name = fs[i].name.toLowerCase();
        if (name.includes(".png")) {
            let buf = await IO.LoadBinaryFile(fs[i].name);
            let sname = TTPathTool.GetFileNameWithoutExt(name);
            let imgdata = await ImgTool.Bin2ImgDataAsync(buf);
            let ttdata: TTImgData = null;
            if (cutborder)
                ttdata = ImgTool.ImgCut(imgdata);
            else {
                ttdata = ImgTool.ImgFill(imgdata);
            }
            srcrect.push(new MyRect(sname, ttdata));
        }
    }
    let bins = ImgTool.Pack(width, height, border, srcrect);


    let atlas: any = {};
    atlas["packoption"] = {};
    atlas["packoption"]["srcpath"] = path;
    atlas["packoption"]["packwidth"] = width;
    atlas["packoption"]["packheight"] = height;


    for (var j = 0; j < bins.length; j++) {
        let data = ImgTool.CreateImgData(width, height);
        let packjson = null;
        if (j == 0) {
            packjson = atlas;
        }
        else {
            if (atlas["groups"] == undefined) {
                atlas["groups"] = [];
            }
            atlas["groups"].push({});
            packjson = atlas["groups"][j - 1];
        }

        let pngname = IO.GetEditBaseName() + "_pack" + j + ".png";
        packjson["tex"] = pngname;
        packjson["texsize"] = width + "," + height;
        packjson["sprites"] = [];
        for (var i = 0; i < bins[j].rects.length; i++) {


            let r = bins[j].rects[i];
            let jsons: any = {};
            jsons["name"] = r.name;
            jsons["uv"] = r.x + "," + r.y + "," + r.width + "," + r.height;
            jsons["border"] = r.imgdata.borderX1 + "," + r.imgdata.borderY1 + "," + r.imgdata.borderX2 + "," + r.imgdata.borderY2;
            ImgTool.PutToImgData(data, r.imgdata, r.x, r.y);
            packjson["sprites"].push(jsons);
        }
        let pngbuf = await ImgTool.ImgData2PngFileDataAsync(data);
        let url = ImgTool.Bin2Url(pngbuf);
        let img = new DOM.Picture(url);
        img._root.style.width = "512";
        img._root.style.height = "512";
        panel.AddChild(img);
        await IO.SaveBinaryFile(pngname, pngbuf);
    }

    await IO.SaveTextFile(IO.GetEditFileName(), JSON.stringify(atlas, null, 4));
}